package com.authine.cloudpivot.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.json.JSONArray;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.fastjson.JSON;
import com.authine.cloudpivot.domain.Dto.*;
import com.authine.cloudpivot.engine.api.facade.BizObjectFacade;
import com.authine.cloudpivot.engine.api.facade.OrganizationFacade;
import com.authine.cloudpivot.engine.api.model.organization.*;
import com.authine.cloudpivot.engine.api.model.permission.DepartmentScopeModel;
import com.authine.cloudpivot.engine.api.model.runtime.AttachmentModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectModel;
import com.authine.cloudpivot.engine.api.model.runtime.SelectionValue;
import com.authine.cloudpivot.engine.api.model.system.AdminModel;
import com.authine.cloudpivot.engine.api.model.system.RelatedCorpSettingModel;
import com.authine.cloudpivot.engine.domain.organization.Department;
import com.authine.cloudpivot.engine.domain.runtime.BizObject;
import com.authine.cloudpivot.engine.enums.status.WorkflowInstanceStatus;
import com.authine.cloudpivot.engine.enums.type.AdminType;
import com.authine.cloudpivot.engine.enums.type.DefaultPropertyType;
import com.authine.cloudpivot.engine.enums.type.UnitType;
import com.authine.cloudpivot.engine.open.OpenEngineFactory;
import com.authine.cloudpivot.engine.open.service.OpenEngine;
import com.authine.cloudpivot.engine.service.organization.DepartmentService;
import com.authine.cloudpivot.ext.service.ipml.*;
import com.authine.cloudpivot.foundation.orm.api.dml.JPANativeQuery;
import com.authine.cloudpivot.service.CjfxOpenApiService2;
import com.authine.cloudpivot.util.*;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.controller.common.OSSController;
import com.authine.cloudpivot.web.api.util.ReflectUtil;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import com.authine.cloudpivot.web.api.view.organization.UserSelectionVO;
import com.authine.cloudpivot.web.api.view.organization.UserVO;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.imageio.ImageIO;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/test")
@Slf4j
public class TestController extends BaseController {

    private static final String SCHMEA_CODE = "AlarmData";

    private static final String CODE = "yhqkmd";

    private static final String USERID = "6b42ebe5236d4ecd84332710e5285fd0";

    @Autowired
    private CjfxOpenApiService2 cjfxOpenApiService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private QueryReportSqlController queryReportSqlController;
    @Autowired
    private OrganizationFacade organizationFacade;

    @Autowired
    private BizObjectFacade bizObjectFacade;

    @Autowired
    private JPANativeQuery jpaNativeQuery;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    BlowWhistleEvent2ServiceIpml blowWhistleEvent2ServiceIpml;

    @Autowired
    SyncErrorDataServiceImpl syncErrorDataService;

    @Autowired
    SyncResidentServiceImpl syncResidentService;
    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    SyncBaseDataUpdateLogServiceImpl syncBaseDataUpdateLogService;

    @Autowired
    SyncKeyProjectServiceImpl syncKeyProjectService;

    @Autowired
    OSSController oSSController;

    @Autowired
    SyncPetitionresidentImpl syncPetitionresident;

    @GetMapping("/getsq")
    public void getsq(){
        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject("concentrateDemand12345", "8e20cb8730ee456aa545a31b3e4bf6f0");
        System.out.println(1);
    }

    @GetMapping("/ex")
    public void excelData(){

        String querdep = "SELECT id,name FROM `h_org_department` where queryCode like '1_1#2_1#979182861#979182862%' and REGEXP_like(name,'街道|社区|村')";
        List<Map<String,Object>> depList = jpaNativeQuery.getList(querdep, null, null);
        Map<String, String> nameById = depList.stream()
                .collect(Collectors.toMap(
                        map -> (String) map.get("name"), // key为ID
                        map -> (String) map.get("id")  // value为姓名
                ));
        String fileName = "D:\\3.28全区风险隐患问题情况汇总.xls";
        List<DemoData> list = EasyExcel.read(fileName).head(DemoData.class).sheet().doReadSync();

        for (DemoData data : list) {
            makeData(data,nameById);
            log.info("读取到数据:{}", new Gson().toJson(data));

        }
    }
    @GetMapping("/te")
    public String te(){
        return "123";
    }

    @GetMapping("/rollback")
    @Transactional
    public void roolback(){
        String sql = "SELECT\n" +
                "\tt1.id,\n" +
                "\tt1.belongjd jd,\n" +
                "\tt1.belongsq sq,\n" +
                "\tt1.belongwg wg \n" +
                "FROM\n" +
                "\tiknn4_yhqkmd t1";
        List<Map<String,String>> list =jpaNativeQuery.getList(sql, null, null);
        for (Map<String,String> map:list){
            String wg = map.get("wg");
            String sq = map.get("sq");
            String jd = map.get("jd");
            String depId = (wg != null && !wg.isEmpty()) ? wg :
                    ((sq != null && !sq.isEmpty()) ? sq : jd);
            String id = map.get("id");
            String depSql = String.format("SELECT\n" +
                    "\tt1.id,\n" +
                    "\tt1.queryCode,\n" +
                    "\tt2.userId\n" +
                    "FROM\n" +
                    "\th_org_department t1\n" +
                    "\tLEFT JOIN h_org_dept_user t2 ON t1.id = t2.deptId\n" +
                    "\twhere t1.id = '%s' and t2.deleted =0  limit 1",depId);
            List<Map<String,String>> list1 = jpaNativeQuery.getList(depSql, null, null);
            if (CollectionUtils.isNotEmpty(list1)){
                Map<String, String> stringStringMap = list1.get(0);
                String bmid = stringStringMap.get("id");
                String queryCode = stringStringMap.get("queryCode");
                String userId = stringStringMap.get("userId");
                String llysql = String.format("update iknn4_yhqkmd set ownerDeptQueryCode ='%s',ownerDeptId ='%s',owner = '%s',creater = '%s',createdDeptId ='%s'  where id = '%s'",queryCode,bmid,userId,userId,bmid,id);
                Query nativeQuery = entityManager.createNativeQuery(llysql);
                nativeQuery.executeUpdate();
            }
        }
    }
    private void makeData(DemoData data,Map<String,String> dep){
        String jd = data.getJd();
        String sq = data.getSq();
        String wg = data.getWg();
        String wgname = wg.replaceFirst(".*社区", "").trim();
        Map<String,Object> map = new HashMap<>();
        map.put("belongjd",dep.get(jd));
        map.put("belongsq",dep.get(sq));
        String sql = String.format("SELECT id,name FROM `h_org_department` where name = '%s' and parentId = '%s'",wgname,dep.get(sq));
        List<Map<String,Object>> wgList = jpaNativeQuery.getList(sql, null, null);
        if (CollectionUtils.isNotEmpty(wgList)){
            map.put("belongwg",wgList.get(0).get("id"));
        }
        map.put("name",wg+"开福区基层治理风险隐患情况摸底表");
        map.put("dxwglx",data.getWglx());
        map.put("wgqyfw",data.getWgqy());
        map.put("wgzjlxdh",data.getWgz());
        map.put("wgll",data.getWgll());

        String aq = data.getAq();
        if (StringUtils.isNotBlank(aq)){
            map.put("wgzyfxyh","安全零事故");
            map.remove("jmlsf");
            map.remove("zalfa");
            map.remove("fwljm");
            map.remove("hjlwr");
            map.remove("qt");
            if (aq.contains("1.")&&aq.contains("2.")){
                String cleanedAq = aq.replaceAll("[\\s\\r\\n]+", "");
                String regex = "^(\\d+)\\..*";
                Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
                Matcher matcher = pattern.matcher(aq); // 使用原始的 aq 字符串，而不是 cleanedAq
                List<String> list = new ArrayList<>();
                while (matcher.find()) {
                    list.add(matcher.group().trim().replaceFirst("^\\d+\\.", ""));
                }
                if (CollectionUtils.isNotEmpty(list)){
                    for (String s:list){
                        map.put("aqlsg",s);
                        saveData(map);
                    }
                }
                System.out.println(1);
            }else {
                map.put("aqlsg",aq);
                saveData(map);
            }
        }
        String jm = data.getJm();
        if (StringUtils.isNotBlank(jm)){
            map.put("wgzyfxyh","居民零上访");
            map.remove("aqlsg");
            map.remove("zalfa");
            map.remove("fwljm");
            map.remove("hjlwr");
            map.remove("qt");
            if (jm.contains("1.")&&jm.contains("2.")){
                String cleanedAq = jm.replaceAll("[\\s\\r\\n]+", "");
                String regex = "^(\\d+)\\..*";
                Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
                Matcher matcher = pattern.matcher(jm); // 使用原始的 aq 字符串，而不是 cleanedAq
                List<String> list = new ArrayList<>();
                while (matcher.find()) {
                    list.add(matcher.group().trim().replaceFirst("^\\d+\\.", ""));
                }
                if (CollectionUtils.isNotEmpty(list)){
                    for (String s:list){
                        map.put("jmlsf",s);
                        saveData(map);
                    }
                }
                System.out.println(1);
            }else {
                map.put("jmlsf",jm);
                saveData(map);
            }
        }
        String za = data.getZa();
        if (StringUtils.isNotBlank(za)){
            map.put("wgzyfxyh","治安零发案");
            map.remove("aqlsg");
            map.remove("jmlsf");
            map.remove("fwljm");
            map.remove("hjlwr");
            map.remove("qt");
            if (za.contains("1.")&&za.contains("2.")){
                String cleanedAq = za.replaceAll("[\\s\\r\\n]+", "");
                String regex = "^(\\d+)\\..*";
                Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
                Matcher matcher = pattern.matcher(za); // 使用原始的 aq 字符串，而不是 cleanedAq
                List<String> list = new ArrayList<>();
                while (matcher.find()) {
                    list.add(matcher.group().trim().replaceFirst("^\\d+\\.", ""));
                }
                if (CollectionUtils.isNotEmpty(list)){
                    for (String s:list){
                        map.put("zalfa",s);
                        saveData(map);
                    }
                }
                System.out.println(1);
            }else {
                map.put("zalfa",za);
                saveData(map);
            }
        }
        String fw = data.getFw();
        if (StringUtils.isNotBlank(fw)){
            map.put("wgzyfxyh","服务零距离");
            map.remove("aqlsg");
            map.remove("jmlsf");
            map.remove("zalfa");
            map.remove("hjlwr");
            map.remove("qt");
            if (fw.contains("1.")&&fw.contains("2.")){
                String cleanedAq = fw.replaceAll("[\\s\\r\\n]+", "");
                String regex = "^(\\d+)\\..*";
                Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
                Matcher matcher = pattern.matcher(fw); // 使用原始的 aq 字符串，而不是 cleanedAq
                List<String> list = new ArrayList<>();
                while (matcher.find()) {
                    list.add(matcher.group().trim().replaceFirst("^\\d+\\.", ""));
                }
                if (CollectionUtils.isNotEmpty(list)){
                    for (String s:list){
                        map.put("fwljm",s);
                        saveData(map);
                    }
                }
                System.out.println(1);
            }else {
                map.put("fwljm",fw);
                saveData(map);
            }
        }
        String hj = data.getHj();
        if (StringUtils.isNotBlank(hj)){
            map.put("wgzyfxyh","环境零污染");
            map.remove("aqlsg");
            map.remove("jmlsf");
            map.remove("zalfa");
            map.remove("fwljm");
            map.remove("qt");
            if (hj.contains("1.")&&hj.contains("2.")){
                String cleanedAq = hj.replaceAll("[\\s\\r\\n]+", "");
                String regex = "^(\\d+)\\..*";
                Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
                Matcher matcher = pattern.matcher(hj); // 使用原始的 aq 字符串，而不是 cleanedAq
                List<String> list = new ArrayList<>();
                while (matcher.find()) {
                    list.add(matcher.group().trim().replaceFirst("^\\d+\\.", ""));
                }
                if (CollectionUtils.isNotEmpty(list)){
                    for (String s:list){
                        map.put("hjlwr",s);
                        saveData(map);
                    }
                }
                System.out.println(1);
            }else {
                map.put("hjlwr",hj);
                saveData(map);
            }
        }
        String qt = data.getQt();
        if (StringUtils.isNotBlank(qt)){
            map.put("wgzyfxyh","其它");
            map.remove("aqlsg");
            map.remove("jmlsf");
            map.remove("zalfa");
            map.remove("fwljm");
            map.remove("hjlwr");
            if (qt.contains("1.")&&qt.contains("2.")){
                String cleanedAq = qt.replaceAll("[\\s\\r\\n]+", "");
                String regex = "^(\\d+)\\..*";
                Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
                Matcher matcher = pattern.matcher(qt); // 使用原始的 aq 字符串，而不是 cleanedAq
                List<String> list = new ArrayList<>();
                while (matcher.find()) {
                    list.add(matcher.group().trim().replaceFirst("^\\d+\\.", ""));
                }
                if (CollectionUtils.isNotEmpty(list)){
                    for (String s:list){
                        map.put("qt",s);
                        saveData(map);
                    }
                }
                System.out.println(1);
            }else {
                map.put("qt",qt);
                saveData(map);
            }
        }


    }

    private void saveData(Map<String,Object> map){
        BizObjectModel bizObjectModel = new BizObjectModel(CODE, map, Boolean.FALSE);
        bizObjectModel.setSequenceStatus(WorkflowInstanceStatus.COMPLETED.toString());
        bizObjectFacade.saveBizObjectModel(USERID,bizObjectModel,null);
    }


    @GetMapping("/t")
    public void t(){
        blowWhistleEvent2ServiceIpml.pushTimedOutToDo();
    }
    @PostMapping("/tt")
    public void tt(@RequestBody Map<String,Date> map){
        syncErrorDataService.processCs(map.get("startTime"),map.get("endTime"));
    }
    @GetMapping("/tc")
    public void tc(){
        syncErrorDataService.pushTimedOutToDo();
    }

    @GetMapping("/t3")
    public void t3(){syncBaseDataUpdateLogService.syncBaseDataUpdateLog();}

    @GetMapping("/t4")
    public void t4(){
        syncKeyProjectService.notice(true);
    }

    @GetMapping("/xf")
    public void xf(){
        syncPetitionresident.notice();
    }

    @GetMapping("/issatisfied")
    public void xcxmy(){
        syncBaseDataUpdateLogService.syncChuishao();
    }

    @GetMapping("/checkIdCard")
    public void checkIdCard(){
        syncResidentService.syncResidentAge();
    }

    @GetMapping("/t6")
    public void processclsx(){
        String queryTypeSql = "select sjzt,yjfl,ejfl,sjfl,blsx from ikhmj_matters where blsx > 0";
        List<Map<String,Object>> listType = jpaNativeQuery.getList(queryTypeSql, null, null);
        String sql = String.format("select id,Dropdown1685712329221 sjzt,Dropdown1685712342343 yjfl,ejfl,sjfl from ikhmj_chuishao_001 ");
        List<Map<String,Object>> list = jpaNativeQuery.getList(sql, null, null);
        for (Map<String,Object> map : list){
            String objectId =(String) map.get("id");
            String sjzt =  (String) map.get("sjzt");
            String yjfl = (String)map.get("yjfl");
            String ejfl = (String)map.get("ejfl");
            String sjfl = (String)map.get("sjfl");
            BigDecimal timeByType = getTimeByType(listType, sjzt, yjfl, ejfl, sjfl);
            if (timeByType!=null){
                BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject("chuishao_001",objectId);
                bizObject.put("blsx",timeByType);
                bizObjectFacade.saveBizObject(bizObject.getCreater().getId(), bizObject, Boolean.TRUE);
            }

        }
    }

    public BigDecimal getTimeByType(List<Map<String,Object>> listType, String sjzt, String yjfl, String ejfl, String sjfl){
        List<Map<String, Object>> sjzt1 = listType.stream().filter(map -> map.get("sjzt").equals(sjzt)).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(sjzt1)){
            if (StringUtils.isNotBlank(yjfl)){
                List<Map<String, Object>> yjfl1 = sjzt1.stream().filter(map -> map.get("yjfl").equals(yjfl)).collect(Collectors.toList());
                if (yjfl1.size()==1){
                    return (BigDecimal) yjfl1.get(0).get("blsx");
                }
                if (CollectionUtils.isNotEmpty(yjfl1)){
                    if (StringUtils.isNotBlank(ejfl)){
                        List<Map<String, Object>> ejfl1 = yjfl1.stream().filter(map -> map.get("ejfl").equals(ejfl)).collect(Collectors.toList());
                        if (ejfl1.size()==1){
                            return (BigDecimal) ejfl1.get(0).get("blsx");
                        }
                        if (CollectionUtils.isNotEmpty(ejfl1)){
                            if (StringUtils.isNotBlank(sjfl)){
                                List<Map<String, Object>> sjfl1 = ejfl1.stream().filter(map -> map.get("sjfl").equals(sjfl)).collect(Collectors.toList());
                                if (sjfl1.size()==1){
                                    return (BigDecimal) sjfl1.get(0).get("blsx");
                                }
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    @GetMapping("/t5")
    @Transactional
    public void processCzjData(){
        String sql = String.format("SELECT * FROM `iknn4_zdxmgzapb`");
        List<Map<String,Object>> list = jpaNativeQuery.getList(sql, null, null);
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(list)){
            for (Map<String,Object> map : list){
                String id =(String) map.get("id");
                String createId =(String) map.get("creater");

                BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject("zdxmgzapb", id);
                String newSQl = String.format("SELECT id,jdqk,LongText1723105434167 as wtkl FROM `iknn4_xmjdqkb` where parentId = '%s' order by gjsj desc limit 1",id);
                List<Map<String,Object>> list1 = jpaNativeQuery.getList(newSQl, null, null);
                if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(list1)){
                    bizObject.put("bzzxjd",list1.get(0).get("jdqk"));
                    bizObject.put("zxjdczwtykn",list1.get(0).get("wtkl"));
                    String zbId = (String) list1.get(0).get("id");
                    String fileSql = String.format("select * from h_biz_attachment where bizObjectId = '%s' and schemaCode = 'xmjdqkb'",zbId);
                    List<Map<String,Object>> list2 = jpaNativeQuery.getList(fileSql, null, null);
                    if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(list2)){
                        for (Map<String,Object> files : list2){
                            String insertSql = String.format("INSERT INTO `cloudpivot`.`h_biz_attachment` (`id`, `bizObjectId`, `bizPropertyCode`, `createdTime`, `creater`, `fileExtension`, `fileSize`, `base64ImageStr`, `mimeType`, `name`,  `refId`, `schemaCode`) VALUES ('%s', '%s', 'zxjdfj', NOW(), '%s', '%s', %s, NULL, '%s', '%s', '%s', 'zdxmgzapb')", UUID.fastUUID().toString(), id, createId, files.get("fileExtension"), files.get("fileSize"), files.get("mimeType"), files.get("name"), files.get("refId"));
                            Query nativeQuery = entityManager.createNativeQuery(insertSql);
                            nativeQuery.executeUpdate();
                        }
                    }
                    bizObjectFacade.saveBizObject(createId, bizObject, Boolean.TRUE);
                }
            }
        }
    }

    public Boolean checkUrl(String refId) {
        String url = "http://121.40.204.45/api/api/fileServer/attachment?refId="+refId;
        try {
            new URI(url);
            return true;
        } catch (URISyntaxException e) {
            return false;
        }
    }
    /**
     * 处理特殊字符文件
     */
    @Transactional
    @GetMapping("/processOssFile")
    public void processOssFile(){
        String sql = "select * from h_biz_attachment  where mimeType like '%image%' and schemaCode = 'securityInspection_test' and id = '2c9b50438fbd8a07018fbe26dda81247'";
        List<Map<String,Object>> list = jpaNativeQuery.getList(sql, null, null);
        for (Map<String, Object> map : list){
            String id = MapUtils.getString(map,"id");
            String refId = MapUtils.getString(map, "refId");
            Boolean checkUrl = checkUrl(refId);
            if (!checkUrl){
                //生成新的id
                String newName = UUID.fastUUID().toString();
                String newFilename ="";
                int dotIndex = refId.lastIndexOf('.');
                if (dotIndex != -1) {
                    String extension = refId.substring(dotIndex);
                    newFilename = newName + extension;
                }
                if (StringUtils.isNotBlank(newFilename)){
                    //替换oss
                    OssUtil.UpdateFileName(refId,newFilename);
                    //更新数据库
                    String updateSql =String.format("update h_biz_attachment set refId = '%s' where id = '%s'",newFilename,id);
                    System.out.println(1);
                    Query nativeQuery = entityManager.createNativeQuery(updateSql);
                    nativeQuery.executeUpdate();
                }
            }
        }
    }
    @GetMapping("/processResidentAddress")
    public void processResidentAddress(){
        String querList = "SELECT id,domicileAddress,registeredAddress FROM `iknn4_resident`  where TRIM(domicileAddress) <> '' and registeredAddress is null ";
//        String querList = "SELECT * FROM `iknn4_resident`  where id = '0736ad3664e24cc8b09c9ef6d59ea098'";
        List<Map<String,Object>> list = jpaNativeQuery.getList(querList, null, null);
        // 线程数量
        int numberOfThreads = 10;
        int chunkSize = list.size() / numberOfThreads;

        // 创建线程池
        ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);

        // 提交任务
        List<Future<?>> futures = new ArrayList<>();
        for (int i = 0; i < numberOfThreads; i++) {
            int start = i * chunkSize;
            int end = (i == numberOfThreads - 1) ? list.size() : (i + 1) * chunkSize;
            List<Map<String,Object>> subList = list.subList(start, end);

            // 提交任务到线程池
            Future<?> future = executor.submit(() -> process(subList));
            futures.add(future);
        }

        // 等待所有任务完成
        for (Future<?> future : futures) {
            try {
                future.get(); // 等待任务完成
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 关闭线程池
        executor.shutdown();
    }

    private void process(List<Map<String,Object>> list){
        if (CollectionUtils.isNotEmpty(list)){
            for (Map<String, Object> resident : list){
                BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject("resident",(String)resident.get("id"));
                if (StringUtils.isNotBlank(bizObject.getString("domicileAddress"))){
                    JSONObject result = cjfxOpenApiService.geo(bizObject.getString("domicileAddress"));
                    if (result.containsKey("geocodes")){
                        JSONArray o =(JSONArray) result.get("geocodes");
                        if (!Objects.isNull(o)){
                            JSONObject gdAddress =(JSONObject) o.get(0);
                            JSONObject newAddress = new JSONObject();
                            newAddress.put("provinceName",gdAddress.getStr("province"));
                            newAddress.put("cityName",gdAddress.getStr("city"));
                            newAddress.put("districtName",gdAddress.getStr("district"));
                            newAddress.put("address",bizObject.getString("domicileAddress"));//用原地址或高德地址
                            String location = gdAddress.getStr("location");
                            String[] split = location.split(",");
                            newAddress.put("lng",split[0]);
                            newAddress.put("lat",split[1]);
                            newAddress.put("adcode",gdAddress.getStr("adcode"));
                            newAddress.put("provinceAdcode","");
                            newAddress.putOnce("cityAdcode","");
                            newAddress.putOnce("districtAdcode","");
                            bizObject.put("registeredAddress",newAddress);
                            bizObjectFacade.saveBizObject(bizObject.getCreater().getId(), bizObject, Boolean.TRUE);
                        }
                    }
                }
            }
        }
    }

    @GetMapping("/processPhoto")
    @Transactional
    public void processPhoto(){
        String querysql = "SELECT\n" +
                "\ta.id,\n" +
                "\ta.picobj,\n" +
                "\tat.refId,\n" +
                "\tat.id attid\n" +
                "FROM\n" +
                "\t`ikhmj_alarmdata` a\n" +
                "\tLEFT JOIN h_biz_attachment AT ON a.id = AT.bizObjectId \n" +
                "WHERE\n" +
                "\ta.picobj not like '%=null%' and a.createdTime > '2024-07-04 00:00:00'";
        List<Map<String,Object>> list = jpaNativeQuery.getList(querysql, null, null);
        for (Map<String, Object> map : list) {
            String input =(String) map.get("picobj");
            // 创建最终的JSON对象
            JSONObject result = new JSONObject();

            // 手动解析字符串
            input = input.substring(1, input.length() - 1); // 去掉最外层的中括号
            String[] items = input.split("}, \\{"); // 分割每个对象

            for (String item : items) {
                item = item.replaceAll("(^\\{)|(\\}$)", ""); // 去掉每个对象的花括号
                int sepIndex = item.indexOf('=');
                String key = item.substring(0, sepIndex).trim();
                String value = item.substring(sepIndex + 1).trim();
                // 修正key
//                key = "\"" + key + "\""; // 将key包裹在引号中

                // 修正value
                if (!value.startsWith("[")) {
                    value = "[" + value;
                }
                if (!value.endsWith("]")) {
                    value = value + "]";
                }
                // 将value解析为JSONArray
                JSONArray jsonArray =JSONUtil.parseArray(value);
                result.put(key, jsonArray);
            }
            List<Map<String, Object>> attachmentModels = new ArrayList<>();
            for (String key : result.keySet()) {
                String ref =(String) map.get("refId");
                String attid =(String) map.get("attid");
                if(ref.equals(key)){
                    JSONArray o =(JSONArray) result.get(key);
                    JSONObject picobj =(JSONObject) o.get(0);
                    Integer objBottom = picobj.getInt("objBottom");
                    Integer objLeft = picobj.getInt("objLeft");
                    Integer objRight = picobj.getInt("objRight");
                    Integer objTop = picobj.getInt("objTop");
                    OpenEngine openEngine = OpenEngineFactory.getOpenEngine();
                    String refId =key.replaceAll("\"", "");
                    InputStream inputStream = openEngine.downloadFile(refId);
                    InputStream takephoto = takephoto(inputStream, objBottom, objLeft, objRight, objTop);
                    UUID uuid = UUID.randomUUID();
                    String fileName = uuid + ".jpg";
                    String newrefId = openEngine.uploadFile(fileName,takephoto);
                    String sql = String.format("update h_biz_attachment set refId = '%s' where id = '%s';",newrefId,attid);
                    Query nativeQuery = entityManager.createNativeQuery(sql);
                    nativeQuery.executeUpdate();
                }
            }
        }
    }

    private InputStream takephoto(InputStream input,Integer objBottom,Integer objLeft,Integer objRight,Integer objTop){
        try {
            BufferedImage image = ImageIO.read(input);

        // 获取Graphics2D对象用于绘图
        Graphics2D g2d = image.createGraphics();

        // 设置画笔颜色和粗细
        g2d.setColor(Color.RED);
        g2d.setStroke(new BasicStroke(6)); // 边框宽度

        // 假设这是从接口获取的原始标注框坐标和图片尺寸
        int originalWidth = 8192;
        int originalHeight = 8192;
        int imgWidth = 1920; // Java环境中canvas的宽度（即BufferedImage的宽度）
        int imgHeight = 1080; // Java环境中canvas的高度（即BufferedImage的高度）



// 换算坐标
        double widthCoefficient = (double) imgWidth / originalWidth;
        double heightCoefficient = (double) imgHeight / originalHeight;

        int scaledLeft = (int) (objLeft * widthCoefficient);
        int scaledTop = (int) (objTop * heightCoefficient);
        int scaledRight = (int) (objRight * widthCoefficient);
        int scaledBottom = (int) (objBottom * heightCoefficient);

        // 绘制矩形
        g2d.drawRect(scaledLeft, scaledTop, scaledRight - scaledLeft, scaledBottom - scaledTop);

        // 释放资源
        g2d.dispose();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        InputStream modifiedImageStream = new ByteArrayInputStream(outputStream.toByteArray());
        return modifiedImageStream;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @GetMapping("/xf")
    public void xfData(){
        HashMap<String, String> params = new HashMap<>(2);
        params.put("username", "block");
        params.put("password", "block_119");
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set(HttpHeaders.CONTENT_TYPE, "application/json");
        HttpEntity<Object> httpEntity = new HttpEntity<>(params, httpHeaders);
        ResponseEntity<JSONObject> response = restTemplate.postForEntity("http://222.240.203.94:11123/block/login", httpEntity, JSONObject.class);
        JSONObject body = response.getBody();
        String token  =(String) body.get("token");
        String queryBlockAddress = "SELECT bm as wgId,jwd FROM `ilrv7_jwdsj`";
        List<BlockAddressDtoList> blockAddressDtoList = jpaNativeQuery.getList(queryBlockAddress, null, null);
        String queryblockDept = "SELECT id,name,parentId FROM `h_org_department` where deleted = 0 and (id <> '06ef8c9a3f3b6669a34036a3001e6340' and id <> '1803c80ed28a3e25871d58808019816e')";
        List<BlockDeptDtoList> blockDeptDtoList = jpaNativeQuery.getList(queryblockDept,null,null);
        String queryblockUser = "SELECT\n" +
                "\tu.id AS userId,\n" +
                "\tu.NAME AS userName,\n" +
                "\tu.mobile,\n" +
                "\tu.departmentId AS depId,\n" +
                "\tt.zysf userType\n" +
                "FROM\n" +
                "\t`h_org_user` u\n" +
                "\tleft join ikhmj_txl t on u.id = t.ry\n" +
                "WHERE\n" +
                "\tu.deleted = 0 \n" +
                "\tAND u.mobile IS NOT NULL";
        List<BlockUserDtoList> blockUserDtoList = jpaNativeQuery.getList(queryblockUser,null,null);
        String queryblockUserDept = "SELECT id,deptId as depId,userId FROM `h_org_dept_user` where deleted = 0";
        List<BlockUserDeptDtoList> blockUserDeptDtoList = jpaNativeQuery.getList(queryblockUserDept,null,null);
        XFPutDataDTO xfPutDataDTO =new XFPutDataDTO();
        xfPutDataDTO.setBlockAddressDtoList(blockAddressDtoList);
        xfPutDataDTO.setBlockDeptDtoList(blockDeptDtoList);
        xfPutDataDTO.setBlockUserDeptDtoList(blockUserDeptDtoList);
        xfPutDataDTO.setBlockUserDtoList(blockUserDtoList);
        HttpHeaders httpHeaders2 = new HttpHeaders();
        httpHeaders2.set(HttpHeaders.CONTENT_TYPE, "application/json");
        httpHeaders2.setBearerAuth(token);
        HttpEntity<Object> httpEntity2 = new HttpEntity<>(xfPutDataDTO, httpHeaders2);
        ResponseEntity<JSONObject> response2 = restTemplate.postForEntity("http://222.240.203.94:11123/block/save", httpEntity2, JSONObject.class);
        System.out.println(1);

    }


    @GetMapping("/processdata")
    public void processdata() {
        String querySql = "select * from ikhmj_alarmdata where belong_community is null limit 0,4990";
        List<Map<String,Object>> list = jpaNativeQuery.getList(querySql, null, null);
        for (Map<String, Object> alarm : list){
            BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject("AlarmData",(String)alarm.get("id"));
//            BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject("cameraInformat",(String)alarm.get("id"));
            if (Objects.nonNull(bizObject)){
                String longitude =(String) bizObject.get("longitude");
                String latitude =(String) bizObject.get("latitude");
                String location = longitude + "," + latitude;
                JSONObject convert = cjfxOpenApiService.convert(location);
                JSONObject address = cjfxOpenApiService.getAddress(convert.getStr("locations"));
                JSONObject regeocode = address.getJSONObject("regeocode");
                String formattedAddress = regeocode.getStr("formatted_address");
                //部门
                String departmentName = null;
                if (!MapUtils.isEmpty(regeocode)) {
                    JSONObject addressComponent = regeocode.getJSONObject("addressComponent");
                    if (!MapUtils.isEmpty(addressComponent)) {
                        departmentName = addressComponent.getStr("township");
                        // 组装地址控件数据
                        String province = addressComponent.getStr("province");
                        String city = addressComponent.getStr("city");
                        String district = addressComponent.getStr("district");
                        String residueAddress = formattedAddress.replace(province, "").replace(city, "").replace(district, "");
                    }
                }
                //街道
                String jdDeptId = null;
                if (StringUtils.isNotBlank(departmentName)) {
                    List<Department> departments = departmentService.getDepartmentsByName(departmentName, Boolean.FALSE);
                    if (CollectionUtils.isNotEmpty(departments)) {
                        jdDeptId = departments.get(0).getId();
                        String deptName = departments.get(0).getName();
                        // 所属街道（部门控件）
                    }
                }
                String sqDeptId = null;
                if (StringUtils.isNotBlank(jdDeptId)) {
                    List<Map<String, Object>> sqJwd = queryReportSqlController.getJdJwd(jdDeptId);
                    double[] doublesME = CoordtransformUtils.WGS84toMercator(Double.parseDouble(longitude), Double.parseDouble(latitude));
                    Point2D.Double aDouble = new Point2D.Double(doublesME[0], doublesME[1]);
                    for (Map<String, Object> map : sqJwd) {
                        String jwd = MapUtils.getString(map, "jwd");
                        if (StringUtils.isBlank(jwd)) {
                            continue;
                        }
                        List<Point2D.Double> doubles = PolygonUtil.parsePointDoubles(jwd);
                        boolean inPolygon = PolygonUtil.isInPolygon(aDouble, doubles);
                        if (inPolygon) {
                            // 社区部门id
                            sqDeptId = MapUtils.getString(map, "id");
                            break;
                        }
                    }
                }
                String wgDeptId = null;
                if (StringUtils.isNotBlank(sqDeptId)) {
                    List<Map<String, Object>> wgJwd = queryReportSqlController.getJdJwd(sqDeptId);
                    double[] doublesME = CoordtransformUtils.WGS84toMercator(Double.parseDouble(longitude), Double.parseDouble(latitude));
                    Point2D.Double aDouble = new Point2D.Double(doublesME[0], doublesME[1]);
                    for (Map<String, Object> map : wgJwd) {
                        String jwd = MapUtils.getString(map, "jwd");
                        if (StringUtils.isBlank(jwd)) {
                            continue;
                        }
                        List<Point2D.Double> doubles = PolygonUtil.parsePointDoubles(jwd);
                        boolean inPolygon = PolygonUtil.isInPolygon(aDouble, doubles);
                        if (inPolygon) {
                            // 网格部门id
                            wgDeptId = MapUtils.getString(map, "id");
                            break;
                        }
                    }
                }
                if (StringUtils.isBlank(sqDeptId)&&StringUtils.isBlank(wgDeptId)) {
                    String channelCode =(String) bizObject.get("channelCode");
                    String querycamara =String.format("SELECT * FROM `ilrv7_camerainformat` where channel_code = '%s' and belong_jd is not null limit 1",channelCode);
                    List<Map<String,Object>> list1 = jpaNativeQuery.getList(querycamara, null, null);
                    if (CollectionUtils.isNotEmpty(list1)){
                        sqDeptId =(String) list1.get(0).get("belong_sq");
                        wgDeptId =(String) list1.get(0).get("belong_wg");
                    }
                }
                DepartmentModel department = organizationFacade.getDepartment(jdDeptId, false);
                DepartmentModel department1 = organizationFacade.getDepartment(sqDeptId, false);
                DepartmentModel department2 = organizationFacade.getDepartment(wgDeptId, false);
//                System.out.println(department.getName()+department1.getName()+ department2.getName());
                    if (StringUtils.isNotBlank(jdDeptId)){
                        bizObject.put("belong_street",jdDeptId);
                    }
                    if (StringUtils.isNotBlank(sqDeptId)){
                        bizObject.put("belong_community",sqDeptId);
                    }
                    if (StringUtils.isNotBlank(wgDeptId)){
                        bizObject.put("belong_grid",wgDeptId);
                    }
                    bizObjectFacade.saveBizObject(bizObject.getCreater().getId(), bizObject, Boolean.TRUE);

            }
        }
        System.out.println("==========end==================");
    }


    /**
     * 住建经纬度
     * @return
     */
    @GetMapping("/zj")
    public Result testzj(@RequestParam String longitude ,@RequestParam String latitudes ){
        String location = longitude + "," + latitudes;
        JSONObject convert = cjfxOpenApiService.convert(location);
        JSONObject address = cjfxOpenApiService.getAddress(convert.getStr("locations"));
        JSONObject regeocode = address.getJSONObject("regeocode");
        String formattedAddress = regeocode.getStr("formatted_address");
        //部门
        String departmentName = null;
        if (!MapUtils.isEmpty(regeocode)) {
            JSONObject addressComponent = regeocode.getJSONObject("addressComponent");
            if (!MapUtils.isEmpty(addressComponent)) {
                departmentName = addressComponent.getStr("township");
                // 组装地址控件数据
                String province = addressComponent.getStr("province");
                String city = addressComponent.getStr("city");
                String district = addressComponent.getStr("district");
                String residueAddress = formattedAddress.replace(province, "").replace(city, "").replace(district, "");
            }
        }
        //街道
        String jdDeptId = null;
        if (StringUtils.isNotBlank(departmentName)) {
            List<Department> departments = departmentService.getDepartmentsByName(departmentName, Boolean.FALSE);
            if (CollectionUtils.isNotEmpty(departments)) {
                jdDeptId = departments.get(0).getId();
                String deptName = departments.get(0).getName();
                // 所属街道（部门控件）
            }
        }
        String sqDeptId = null;
        if (StringUtils.isNotBlank(jdDeptId)) {
            List<Map<String, Object>> sqJwd = queryReportSqlController.getJdJwd(jdDeptId);
//            double[] doublesWGS = CoordtransformUtils.GCJ02toWGS84(Double.parseDouble(longitude), Double.parseDouble(latitudes));
            double[] doublesME = CoordtransformUtils.WGS84toMercator(Double.parseDouble(longitude), Double.parseDouble(latitudes));
            Point2D.Double aDouble = new Point2D.Double(doublesME[0], doublesME[1]);
            for (Map<String, Object> map : sqJwd) {
                String jwd = MapUtils.getString(map, "jwd");
                if (StringUtils.isBlank(jwd)) {
                    continue;
                }
                List<Point2D.Double> doubles = PolygonUtil.parsePointDoubles(jwd);
                boolean inPolygon = PolygonUtil.isInPolygon(aDouble, doubles);
                if (inPolygon) {
                    // 社区部门id
                    sqDeptId = MapUtils.getString(map, "id");
                    break;
                }
            }
        }
        String wgDeptId = null;
        if (StringUtils.isNotBlank(sqDeptId)) {
            List<Map<String, Object>> wgJwd = queryReportSqlController.getJdJwd(sqDeptId);
//            double[] doublesWGS = CoordtransformUtils.GCJ02toWGS84(Double.parseDouble(longitude), Double.parseDouble(latitudes));
            double[] doublesME = CoordtransformUtils.WGS84toMercator(Double.parseDouble(longitude), Double.parseDouble(latitudes));
            Point2D.Double aDouble = new Point2D.Double(doublesME[0], doublesME[1]);
            for (Map<String, Object> map : wgJwd) {
                String jwd = MapUtils.getString(map, "jwd");
                if (StringUtils.isBlank(jwd)) {
                    continue;
                }
                List<Point2D.Double> doubles = PolygonUtil.parsePointDoubles(jwd);
                boolean inPolygon = PolygonUtil.isInPolygon(aDouble, doubles);
                if (inPolygon) {
                    // 网格部门id
                    wgDeptId = MapUtils.getString(map, "id");
                    break;
                }
            }
        }
        DepartmentModel department = organizationFacade.getDepartment(jdDeptId, false);
        DepartmentModel department1 = organizationFacade.getDepartment(sqDeptId, false);
        DepartmentModel department2 = organizationFacade.getDepartment(wgDeptId, false);
        return Result.ok(department.getName()+department1.getName()+ department2.getName());
    }


    @GetMapping("/userTotl")
    @Transactional
    public void userTotal(){
        String sql = "SELECT h1.id,h1.name\n" +
                "        FROM h_org_department h1\n" +
                "        WHERE h1.querycode LIKE  '1_1#3_1#5_1%'\n" +
                "         AND h1.NAME REGEXP '街道|社区|村|网格'\n" +
                "        AND h1.deleted = 0 and id != '2c9a8e6488e8fca60188e912ee421f97'";
        List<Map<String,Object>> list = jpaNativeQuery.getList(sql, null, null);
        for (Map<String, Object> map : list){
            String depId =(String) map.get("id");
            String name = (String) map.get("name");
            String querysql = String.format("SELECT COUNT(DISTINCT(userId)) total\n" +
                    "FROM h_org_dept_user\n" +
                    "WHERE deptId IN (\n" +
                    "    SELECT id\n" +
                    "    FROM (\n" +
                    "        SELECT h1.id,h1.name\n" +
                    "        FROM h_org_department h1\n" +
                    "        WHERE h1.querycode LIKE CONCAT(\n" +
                    "            (SELECT h2.queryCode FROM h_org_department h2 WHERE h2.id = '%s'),\n" +
                    "            '%%'\n" +
                    "        ) AND h1.NAME REGEXP '街道|社区|村|网格'\n" +
                    "        AND h1.deleted = 0\n" +
                    "    ) AS subquery \n" +
                    ");",depId);
            List<Map<String,Object>> list1 = jpaNativeQuery.getList(querysql, null, null);
            Object o = list1.get(0).get("total");
            String deptotal = String.format("select * from dep_user_total where deptId = '%s'",depId);
            List<Map<String,Object>> list2 = jpaNativeQuery.getList(deptotal, null, null);
            if(CollectionUtils.isNotEmpty(list2)){
                String updateSql = String.format("UPDATE dep_user_total SET total = '%s' WHERE deptId = '%s'", o, depId);
                Query nativeQuery = entityManager.createNativeQuery(updateSql);
                nativeQuery.executeUpdate();
            }else {
                String insertSql = String.format("INSERT INTO dep_user_total (`deptId`,`name`,`total`) VALUES ('%s', '%s','%s')", depId,name,o);
                Query nativeQuery = entityManager.createNativeQuery(insertSql);
                nativeQuery.executeUpdate();
            }
        }
    }
}
